package io.clayton.miep.boots;

import io.clayton.miep.config.ComponentConfigurer;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

/**
 * 服务器启动入口类
 */
public class Startup implements WebApplicationInitializer {

	private static final String SPRING_MVC_SERVLET_NAME = "spring-mvc";
	
	private ServletContext ctx;

	/**
	 * 服务器启动调用此方法，在这里可以做配置 作用与web.xml相同
	 */
	@Override
	public void onStartup(ServletContext ctx) throws ServletException {
		
		this.ctx = ctx;
		
		// 注册springMvc的servlet
		addSpringMVC();

		// 注册过滤器
		// servletContext.addFilter(arg0, arg1)

		// 注册监听器
		// servletContext.addListener(arg0);
	}
	
	/**
	 * 注册Spring servlet
	 * @param ctx
	 */
	private void addSpringMVC() {

		// 注册spring mvc 的 servlet
		Dynamic dynamic = ctx.addServlet(SPRING_MVC_SERVLET_NAME, 
				new DispatcherServlet(getWebContext(ComponentConfigurer.class)));

		// 添加springMVC 允许访问的Controller后缀
		dynamic.addMapping("/service/*");

		// 全部通过请用 “/”
		// dynamic.addMapping(/);
		dynamic.setLoadOnStartup(1);
//		dynamic.setMultipartConfig(new MultipartConfigElement(
//				null, MAX_FILE_SIZE, MAX_REQUEST_SIZE, FILE_SIZE_THRESHOLD));
	}

	/**
	 * 通过自定义的配置类来实例化一个Web Application Context
	 * 
	 * @param clazz
	 * @return
	 */
	private WebApplicationContext getWebContext(Class<?>... clazz) {
		AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext();
		webContext.register(clazz);

		return webContext;
	}

}